package top.ezzz.util;

import cn.hutool.extra.mail.MailAccount;
import lombok.extern.slf4j.Slf4j;
import top.ezzz.config.MailConfig;
import top.ezzz.model.ReceiveInfo;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * 使用Hutool辅助发送邮件（基于smtp协议）
 * 使用Hutool辅助接收邮件（基于POP3协议）
 */
@Slf4j
public class MailUtil {

    /**
     * 发送邮件
     */
    public static String send(String to, String subject, String content) {
        // "shenmingkai8037@dingtalk.com", "测试", "测试",
        MailAccount account = MailConfig.SendAccount.getAccount();
        String send = cn.hutool.extra.mail.MailUtil.send(account, to, subject, content, true);
        log.info(send);
        return send;
    }

    public static ReceiveInfo receive() {
        ReceiveInfo result = new ReceiveInfo();
        // 2. 创建会话和存储对象
        Properties account = MailConfig.ReceiveAccount.getAccount();
        Session session = Session.getDefaultInstance(account);
        Message[] messages = null;
        Store store = null;
        Folder inbox = null;
        try {
            store = session.getStore(MailConfig.ReceiveAccount.protocol);
            // 连接服务器（使用Hutool的账号配置）
            store.connect(MailConfig.ReceiveAccount.host, MailConfig.ReceiveAccount.username,
                    MailConfig.ReceiveAccount.password);
            // 3. 打开收件箱
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY); // 只读模式打开
            // 4. 获取邮件列表（最新的邮件在后面）
            if (inbox.isOpen()) {
                messages = inbox.getMessages();
                result.setAddress(inbox.getFullName());
            }
        } catch (Exception e) {
            log.error("邮件连接错误：" + e.getMessage());
        }
        int total = messages.length;
        log.info("收件箱共有 " + total + " 封邮件");
        result.setTotal(total);

        // 控制最大接收数量
        int start = Math.max(0, total - MailConfig.ReceiveAccount.receiveCount);
        for (int i = total - 1; i >= start; i--) {
            try {
                Message message = messages[i];
                ReceiveInfo.Mail mail = new ReceiveInfo.Mail();
                mail.setInd(i + 1);
                mail.setFromFrom(InternetAddress.toString(message.getFrom()));
                mail.setToTo(InternetAddress.toString(message.getRecipients(Message.RecipientType.TO)));
                mail.setSubject(message.getSubject());
                mail.setContent(getTextContent(message));
                mail.setDateMail(message.getSentDate().toString());
                result.getMails().add(mail);
                log.info(mail.toString());
            } catch (Exception e) {
                log.error("邮件解析错误：" + e.getMessage());
            }
        }
        try {
            inbox.close();
            store.close();
        } catch (Exception e) {
            log.error("邮件关闭错误：" + e.getMessage());
        }
        return result;
    }

    /**
     * 提取邮件文本内容（处理文本和HTML格式）
     */
    private static String getTextContent(Part part) throws Exception {
        if (part.isMimeType("text/plain")) {
            // 纯文本内容
            return part.getContent().toString();
        } else if (part.isMimeType("text/html")) {
            // HTML内容，简单去除标签
            String html = part.getContent().toString();
            return html;
            //return html.replaceAll("<[^>]+>", "");
        } else if (part.isMimeType("multipart/*")) {
            // 多部分内容，递归处理
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                String content = getTextContent(multipart.getBodyPart(i));
                if (!content.isEmpty()) {
                    return content;
                }
            }
        }
        return "";
    }

}